package cn.jilian.security.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.jilian.common.config.SpringBeans;
import cn.jilian.common.util.MD5Util;
import cn.jilian.dao.AuthDAO;
import cn.jilian.dao.UserDAO;
import cn.jilian.entity.Auth;
import cn.jilian.entity.Menu;
import cn.jilian.entity.User;
import cn.jilian.security.util.ShiroUtils;
import cn.jilian.sys.service.MenuService;

public class UserRealm extends AuthorizingRealm {


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		User user = ShiroUtils.getUser();
		MenuService menuService = SpringBeans.getBean(MenuService.class);
		Set<String> perms = menuService.getPerms(user, Menu.RANK);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		Map<String, Object> map = new HashMap<>(16);
		map.put("username", username);
		String password = new String((char[]) token.getCredentials());

		UserDAO userMapper = SpringBeans.getBean(UserDAO.class);
		AuthDAO authDAO = SpringBeans.getBean(AuthDAO.class);
		// 查询用户信息
		

		Auth auth=authDAO.findByUsername(username);
		// 账号不存在
		if (auth == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}

		// 密码错误
		if (!StringUtils.equals(MD5Util.GetMD5Code(password+auth.getSalt()), auth.getPass())) {
			throw new IncorrectCredentialsException("账号或密码不正确");
		}
		User user = userMapper.findOne(auth.getFid());
		// 账号锁定
		if (user.getFlag()== 0) {
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
		return info;
	}

}
